package cn.tedu.tmall.admin.account.service.impl;

import cn.tedu.tmall.admin.account.dao.cache.IUserCacheRepository;
import cn.tedu.tmall.admin.account.dao.persist.repository.IUserRepository;
import cn.tedu.tmall.admin.account.dao.persist.repository.IUserRoleRepository;
import cn.tedu.tmall.admin.account.pojo.entity.User;
import cn.tedu.tmall.admin.account.pojo.entity.UserRole;
import cn.tedu.tmall.admin.account.pojo.param.UserAddNewParam;
import cn.tedu.tmall.admin.account.pojo.param.UserUpdateInfoParam;
import cn.tedu.tmall.admin.account.pojo.vo.UserListItemVO;
import cn.tedu.tmall.admin.account.pojo.vo.UserStandardVO;
import cn.tedu.tmall.admin.account.service.IUserService;
import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.po.UserStatePO;
import cn.tedu.tmall.common.pojo.vo.PageData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class UserServiceImpl implements IUserService {

    @Value("${tmall.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private IUserRoleRepository userRoleRepository;
    @Autowired
    private IUserCacheRepository userCacheRepository;

    @Override
    public void addNew(UserAddNewParam userAddNewParam) {

        // 用户名必须唯一
        {
            String username = userAddNewParam.getUsername();
            int count = userRepository.countByUsername(username);
            if (count > 0) {
                String message = "添加用户失败，用户名已经被占用！";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        // 邮箱必须唯一
        {
            String email = userAddNewParam.getEmail();
            int count = userRepository.countByEmail(email);
            if (count > 0) {
                String message = "添加用户失败，电子邮箱已经被占用！";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        // 手机号码必须唯一
        {
            String phone = userAddNewParam.getPhone();
            int count = userRepository.countByPhone(phone);
            if (count > 0) {
                String message = "添加用户失败，手机号码已经被占用！";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        User user = new User();
        BeanUtils.copyProperties(userAddNewParam, user);
        user.setLoginCount(0);
        String rawPassword = user.getPassword();
        String encodedPassword = passwordEncoder.encode(rawPassword);
        user.setPassword(encodedPassword);
        int rows = userRepository.insert(user);
        if (rows != 1) {
            String message = "添加用户失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        Long[] roleIds = userAddNewParam.getRoleIds();
        ArrayList<UserRole> userRoleList = new ArrayList<>();
        for (Long roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }
        rows = userRoleRepository.insertBatch(userRoleList);
        if (rows < 1) {
            String message = "添加用户失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public void updateInfo(Long userId, UserUpdateInfoParam userUpdateInfoParam) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateInfoParam,user);
        user.setId(userId);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改基本信息失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updatePassword(Long userId, String newPassword) {
        String encodedPassword = passwordEncoder.encode(newPassword);
        User user = new User();
        user.setId(userId);
        user.setPassword(encodedPassword);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改密码失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updateAvatar(Long userId, String avatar) {
        User user = new User();
        user.setId(userId);
        user.setAvatar(avatar);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改头像失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void setEnable(Long userId) {
        updateEnableById(userId,ENABLE_STATE_ON);
    }

    @Override
    public void setDisable(Long userId) {
        updateEnableById(userId,ENABLE_STATE_OFF);
    }

    @Override
    public UserStandardVO getStandardById(Long userId) {
        UserStandardVO currentUser = userRepository.getStandardById(userId);
        if (currentUser == null) {
            String message = "获取用户详情失败，尝试访问的用户数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return currentUser;
    }

    @Override
    public PageData<UserListItemVO> list(Integer pageNum) {
        return userRepository.list(pageNum,defaultQueryPageSize);
    }

    @Override
    public PageData<UserListItemVO> list(Integer pageNum, Integer pageSize) {
        return userRepository.list(pageNum,pageSize);
    }

    private void updateEnableById(Long id,Integer enable) {
        if (id == 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        UserStandardVO queryResult = userRepository.getStandardById(id);
        if (queryResult == null) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，当前用户已经处于"
                    + ENABLE_STATE_TEXT[enable] + "状态！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        User user = new User();
        user.setId(id);
        user.setEnable(enable);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，服务器忙，请稍后再次尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        if (enable.equals(ENABLE_STATE_OFF)) {
            UserStatePO userState = userCacheRepository.getUserState(id);
            if (userState != null) {
                userCacheRepository.setUserDisabled(id);
            }
        }

    }

}
